﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Config.Enum;
using Microsoft.AspNet.Membership.OpenAuth;
using PaymentBLL;
using WebTriple7.Class;

namespace WebTriple7.Portal
{
    public partial class LoginExternal : System.Web.UI.Page
    {
        public string ProviderDisplayName = "";
        public string ProviderUserName = "";
        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                ProcessProviderResult();
            }
        }

        private void ProcessProviderResult()
        {
            // Process the result from an auth provider in the request
            var providerName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(providerName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(providerName);

            // Build the redirect url for OpenAuth verification
            var redirectUrl = "~/Portal/LoginExternal.aspx";
            var returnUrl = Request.QueryString["ReturnUrl"];
            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // Verify the OpenAuth payload
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderUserName = authResult.ProviderUserId;

            if (!authResult.IsSuccessful)
            {
                Title = "External login failed";

                txtMess.Text = String.Format("External login {0} failed,", ProviderDisplayName);

                // To view this error, enable page tracing in web.config (<system.web><trace enabled="true"/></system.web>) and visit ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("There was an error verifying authentication with {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            var ctr = new CtrAccount();
            string uName = authResult.ProviderUserId;
            string fName = authResult.UserName;            
            var info = ctr.SelectAccountInfoByName(uName);
            if (info != null)
            {
                AccountSession.Login(info.Id, uName, fName, GetProviderKeyByName(providerName));
                RedirectToReturnUrl();
            }

            int? id = 0;
            ctr.InsertAccount(uName, fName, GetProviderKeyByName(providerName),
                fName, "", 1, ref id);
            if (!(id > 0))
            {
                txtMess.Text = "Lỗi tạo tài khoản";
            }
            else
            {
                AccountSession.Login(id ?? 0, uName, fName, GetProviderKeyByName(providerName));
                RedirectToReturnUrl();
            }
        }
        private int GetProviderKeyByName(string name)
        {
            switch (name)
            {

                case "facebook":
                    return (int)LoginType.Facebook;
                case "google":
                    return (int)LoginType.Google;
                case "yahoo":
                    return (int)LoginType.Yahoo;
            }
            return 0;
        }

        private void RedirectToReturnUrl()
        {
            var returnUrl = Request.QueryString["ReturnUrl"];
            if (!String.IsNullOrEmpty(returnUrl) && OpenAuth.IsLocalUrl(returnUrl))
            {
                Response.Redirect(returnUrl);
            }
            else
            {
                Response.Redirect("~/Portal/Default.aspx");
            }
        }
    }
}